import axios from 'axios'
import store from '@/store'
import { get } from 'lodash'
// import Vue from 'vue'
import { Toast } from 'cube-ui'

import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL:
    process.env.NODE_ENV === 'development' ? '/' : process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
  headers: {
    'Content-Type': 'application/json',
  },
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    config.headers['Authorization'] = `Bearer ${store.state.user.token ||
      getToken()}`
    // console.log(config)
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    // dataAxios 是 axios 返回数据中的 data
    const dataAxios = response.data
    // 这个状态码是和后端约定的
    const { state } = dataAxios

    switch (state) {
      case true:
        break
      default:
        Toast.$create({
          txt: dataAxios.message,
          type: 'error',
        }).show()
        break
    }
    return dataAxios
  },
  (error) => {
    const status = get(error, 'response.status')
    switch (status) {
      case 400:
        error.message = '请求错误'
        break
      case 401:
        error.message = '未授权，请登录'
        break
      case 403:
        error.message = '拒绝访问'
        break
      case 404:
        error.message = `请求地址出错: ${error.response.config.url}`
        break
      case 408:
        error.message = '请求超时'
        break
      case 500:
        error.message = '服务器内部错误'
        break
      case 501:
        error.message = '服务未实现'
        break
      case 502:
        error.message = '网关错误'
        break
      case 503:
        error.message = '服务不可用'
        break
      case 504:
        error.message = '网关超时'
        break
      case 505:
        error.message = 'HTTP版本不受支持'
        break
      default:
        break
    }
    return Promise.reject(error)
  }
)

export default service
